﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.ViewModel.Common.LogTool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace CastingWellEquipmentGUI.Utils
{
    public static class SocketHelper
    {
        public static Socket ClientSocket = null;
        public static bool InitSocket()
        {
            //获取服务器端IP地址和端口号
            IPEndPoint sipep1 = new IPEndPoint(IPAddress.Parse(SystemConfig.dataBaseIpAddress), 5001);
            //创建一个Socket
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ClientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 30000);
            try
            {
                ClientSocket.Connect(sipep1);
                return true;
            }
            catch (Exception ex)
            {
                LogTool.SaveSysLog(ex.Message, "使用Socket连接网关");
                return false;
            }
        }
        public static bool IsSocketConnected(Socket client)
        {
            bool blockingState = client.Blocking;
            try
            {
                byte[] tmp = new byte[1];
                client.Blocking = false;
                client.Send(tmp, 0, 0);
                return false;
            }
            catch (SocketException e)
            {
                // 产生 10035 == WSAEWOULDBLOCK 错误，说明被阻止了，但是还是连接的
                if (e.NativeErrorCode.Equals(10035))
                    return false;
                else
                    return true;
            }
            finally
            {
                client.Blocking = blockingState;    // 恢复状态
            }
        }
    }

    
}
